import _ from "lodash";

import { Code } from "./code";

export const isValue = (value: any) => _.isString(value) || _.isNumber(value);

export const isInitNumber = (value: any) =>
  _.isNumber(value) && !_.isNaN(value);

export const isInitString = (value: any) =>
  _.isString(value) && value.length > 0;

export const isInitValue = (value: any) =>
  isInitNumber(value) || isInitString(value);

const routeSep = "/";
export const routeJoin = (...args: Array<string>) =>
  _.reduce(
    args,
    (acc, cur) =>
      (acc = acc + routeSep + _.compact(_.split(cur, routeSep)).join(routeSep)),
    ""
  );

export const JsonResultUtil = (...args: Array<any>) => {
  let code = Code.success;
  let message = "success";
  let data = null;

  if (args.length === 1) {
    data = args[0];
  } else {
    args.forEach((item, index) => {
      if (typeof item === "number" && index === 0) {
        code = item;
      } else if (typeof item === "string" && index === args.length - 1) {
        message = item;
      } else {
        data = item;
      }
    });
  }
  return { code, message, data };
};

export const ResultBuild = (list: Array<Array<any>>, data: any) => {
  for (const kv of list) {
    const [key, type] = kv;
    const value = data[key];
    if (
      (type === Number && !isInitNumber(value)) ||
      (type === String && !isInitString(value))
    ) {
      return JsonResultUtil(Code.unprocessable_entity, `缺少必要的${key}字段`);
    }
  }
};